#include "..\..\Header\Entity\Image2D.h"
#include <fwLog.h>

int Image2D::Init()
{
	LOGI("Init data\n");
	//Vertex define
	Vertex vertices[4];
	vertices[0].Posotion = Vector3(0.0f, 0.5f, 0.0f);
	vertices[1].Posotion = Vector3(-0.5f, -0.5f, 0.0f);
	vertices[2].Posotion = Vector3(0.5f, -0.5f, 0.0f);

	vertices[0].UV = Vector2(0.0f, 0.0f);
	vertices[1].UV = Vector2(0.0f, 1.0f);
	vertices[2].UV = Vector2(1.0f, 0.0f);
	//vertices[3].UV = Vector2(1.0f, 1.0f);

	GLushort indices[6] = { 0, 1, 2 };

	m_Mesh = new ObjectMesh();
	m_Mesh->BindData(vertices, 3, indices, 3);

	//Texture define
	m_Texture = new ObjectTexture();

	char** strSrcs = String::NewStringArray(1, String::AddString(NULL, BASE_SRC, "Resources/Textures/Dirt.tga"));
	m_Texture->Init(GL_TEXTURE_2D, 1, strSrcs);
	SAFE_DEL_ARRAY_POINTER(strSrcs, 1);

	m_Shader = new ObjectShader();
	char * vs = String::AddString(NULL, BASE_SRC, "Resources/Shaders/Trigangle.vsh");
	char * fs = String::AddString(NULL, BASE_SRC, "Resources/Shaders/Trigangle.fsh");
	m_Shader->InitFormFile(vs, fs);
	SAFE_DEL_ARRAY(vs);
	SAFE_DEL_ARRAY(fs);
	return 0;
}

void Image2D::Update(float)
{

}

void Image2D::Draw()
{
	glUseProgram(m_Shader->m_Program);

	//Bind vertex data
	glBindBuffer(GL_ARRAY_BUFFER, m_Mesh->GetVBO());
	if (m_Shader->m_Position != -1)
	{
		glEnableVertexAttribArray(m_Shader->m_Position);
		glVertexAttribPointer(m_Shader->m_Position, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
	}
	if (m_Shader->m_UV != -1)
	{
		glEnableVertexAttribArray(m_Shader->m_UV);
		glVertexAttribPointer(m_Shader->m_UV, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (char*)0 + sizeof(Vector3) + sizeof(Vector4));
	}

	//Bind vertex index
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Mesh->GetIBO());

	m_Texture->Bind(*m_Shader);

	//draw
	glDrawElements(GL_TRIANGLES, m_Mesh->GetIBOSize(), GL_UNSIGNED_SHORT, 0);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	m_Texture->UnBind();
}

void Image2D::Destroy()
{
	m_Mesh->Destroy();
	SAFE_DEL(m_Mesh);
	m_Texture->Destroy();
	SAFE_DEL(m_Texture);
	SAFE_DEL(m_Shader);
}